package com.webex.ta.hydra.gui.table.celleditor;

import com.webex.ta.hydra.core.Command;
import com.webex.ta.hydra.gui.GuiPackage;
import com.webex.ta.hydra.gui.util.ComponentUtil;

import javax.swing.*;
import javax.swing.table.TableCellEditor;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.util.EventObject;

/**
 * Created by Cisco WebEx.
 * User: vegaz
 * Date: 2010-10-26
 * Time: 10:15:16
 */
public abstract class DialogCellEditor extends HydraCellEditor implements TableCellEditor {
    private JLabel label = new JLabel();
    private String value = "";
    private AbstractEditorDialogComponent editor;
    private EditorDialog dialog;
    private JTable table;


    public DialogCellEditor() {
        label.setBorder(BorderFactory.createLineBorder(Color.gray));
        dialog = new EditorDialog(GuiPackage.getInstance().getIdeFrame(), "");
    }

    protected abstract AbstractEditorDialogComponent getEditorComponent();

    @Override
    public void startCellEditing() {
        editor = getEditorComponent();
        editor.reset();
        editor.setValue(value);
        dialog.setContent(editor);
        dialog.pack();
        ComponentUtil.centerComponentInWindow(dialog);
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                dialog.setVisible(true);
                table.requestFocus();
                fireEditingStopped();
            }
        });

    }

    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
        this.table = table;
        Command command = (Command) value;
        int paramNum = column - 2;
        this.value = command.getParameter(paramNum);
        label.setText(this.value);
        return label;
    }

    public Object getCellEditorValue() {
        if (dialog.response != JOptionPane.YES_OPTION) {
            return value;
        } else {
            return editor.getValue();
        }
    }

    @Override
    public boolean stopCellEditing() {
        dialog.setVisible(false);
        return super.stopCellEditing();
    }

    public boolean isCellEditable(EventObject e) {
        if (e instanceof MouseEvent) {
            return ((MouseEvent) e).getClickCount() >= 2;
        }
        return true;
    }
}
